package com.techsoul.module.accounting.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.Result;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.collection.MapUtils;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.log.annotation.Log;
import com.techsoul.common.log.enums.OperationTypeEnum;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.accounting.enmus.AccountingStatusEnum;
import com.techsoul.module.accounting.pojo.param.AccountingApSaveParam;
import com.techsoul.module.accounting.pojo.param.AccountingApSearchParam;
import com.techsoul.module.accounting.pojo.vo.AccApSkuMonthlySettlementViewVo;
import com.techsoul.module.accounting.pojo.vo.AccountingApViewVo;
import com.techsoul.module.accounting.pojo.vo.AccountingApVo;
import com.techsoul.module.accounting.service.IAccountingApService;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.service.ICustomerService;
import com.techsoul.module.order.enmus.SalesOrderStatusEnum;
import com.techsoul.module.order.pojo.entity.SalesOrder;
import com.techsoul.module.order.pojo.param.SalesOrderItemSaveParam;
import com.techsoul.module.order.pojo.param.SalesOrderItemSearchParam;
import com.techsoul.module.order.pojo.vo.SalesOrderItemVo;
import com.techsoul.module.order.service.ISalesOrderItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 财务应付 Controller
 *
 * @author liuen
 * @date 2021-04-11
 */
@Api(tags = "财务应付")
@RestController
@Slf4j
@RequestMapping("/accounting/accountingAp")
public class AccountingApController {

    @Autowired
    private Result result;

    @Autowired
    private IAccountingApService service;

    @Autowired
    private ISalesOrderItemService salesOrderItemService;

    @Autowired
    private ICustomerService iCustomerService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("新增")
    @Log(title = "财务应付", operationType = OperationTypeEnum.INSERT)
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:insert')")
    @PostMapping
    public Result insert(@Valid @RequestBody AccountingApSaveParam params) {
        return result.success(this.service.insert(params));
    }

    @ApiOperation("批量删除（多个用逗号隔开）")
    @Log(title = "财务应付", operationType = OperationTypeEnum.DELETE)
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:delete')")
    @DeleteMapping("/{ids}")
    public Result batchDelete(@PathVariable String[] ids) {
        return result.success(this.service.batchDelete(Arrays.asList(ids)));
    }

    @ApiOperation("去重")
    @Log(title = "财务应付", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:update')")
    @GetMapping("distinct")
    public Result distinct() {
        this.service.distinct();
        return result.success();
    }

    @ApiOperation("修改")
    @Log(title = "财务应付", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:update')")
    @PutMapping
    public Result update(@Valid @RequestBody AccountingApSaveParam params) {
        return result.success(this.service.update(params));
    }

    @ApiOperation("详情")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") String id) {
        return result.success(this.service.findById(id));
    }

    @ApiOperation("列表")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/search")
    public Result findAll(@RequestBody AccountingApSearchParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        params.setSite(user.getSite());
        return result.success(this.service.findAll(params));
    }
    @ApiOperation("列表")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/searchMyApConfirm")
    public Result searchMyApConfirm(@RequestBody AccountingApSearchParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        params.setSentToSite(user.getSite());
        params.setStatus(AccountingStatusEnum.sent.getEventCode());
        return result.success(this.service.findAll(params));
    }
    @ApiOperation("采购汇总报表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/settlementViewSkuMonthly/{current}/{pageSize}")
    public Result settlementViewSkuMonthly(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {

        return result.success(this.service.settlementViewSkuMonthly(params, current, pageSize));
    }
    @ApiOperation("报表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/settlementViewMonthly/{current}/{pageSize}")
    public Result settlementViewMonthly(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {

        return result.success(this.service.settlementViewMonthly(params, current, pageSize));
    }
    @ApiOperation("列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/search/{current}/{pageSize}")
    public Result findAll(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
       /* if(StringUtils.isNull(params.getJobDateFr())&&StringUtils.isNull(params.getJobDateTo())
                &&StringUtils.isNull(params.getJobDate()) &&StringUtils.isNull(params.getSourceItemId())
                &&StringUtils.isNull(params.getCustSpuId()) &&StringUtils.isNull(params.getCustSkuId())){
            Date today = new Date();
            Date fr= DateUtils.getDateBefore(today,3);
            String datefr = DateUtils.formatDate(fr,"yyyy-MM-dd HH:mm:ss");
            params.setJobDateFr(datefr);
            String dateto = DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
            params.setJobDateTo(dateto);
        }*/
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        params.setSite(user.getSite());
        return result.success(this.service.findAll(params, current, pageSize));
    }
    @ApiOperation("SKU采购列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/findSkuAll/{current}/{pageSize}")
    public Result findSkuAll(@RequestBody AccountingApSearchParam params , @PathVariable Integer current, @PathVariable Integer pageSize){
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        params.setSite(user.getSite());
        return result.success(this.service.findAllWithRt(params, current, pageSize));
    }
    @ApiOperation("列表字段汇总")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/sum")
    public Result sum(@RequestBody AccountingApSearchParam params) {
        return result.success(this.service.sum(params));
    }

    @ApiOperation("列表退单字段汇总")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/returnSum")
    public Result returnSum(@RequestBody AccountingApSearchParam params) {
        return result.success(this.service.returnSum(params));
    }

    @ApiOperation("报表字段汇总")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/settlementViewMonthlySum")
    public Result settlementViewMonthlySum(@RequestBody AccountingApSearchParam params) {
        return result.success(this.service.settlementViewMonthlySum(params));
    }
    @ApiOperation("报表字段汇总")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/settlementViewMonthlyReturnSum")
    public Result settlementViewMonthlyReturnSum(@RequestBody AccountingApSearchParam params) {
        return result.success(this.service.settlementViewMonthlyReturnSum(params));
    }
    @ApiOperation("供应商汇总列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/supplierSumPage/{current}/{pageSize}")
    public Result supplierSumPage(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.supplierSumPage(params, current, pageSize));
    }

    @ApiOperation("供应商-查询结算明细")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("api/suppierViewAccount")
    public Result suppierViewAccountAp(@RequestBody Map map){
        String supplierNo = (String) map.get("supplierNo");
        String dateFrom = (String) map.get("dateFrom");
        String dateTo = (String) map.get("dateTo");
        List<AccountingApVo> retresult = this.service.suppierViewAccount(supplierNo,dateFrom,dateTo);

        return result.success(retresult);
    }
    @ApiOperation("供应商-查询结算明细")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/suppierViewAccount")
    public Result suppierViewAccount(@RequestBody Map map){
        String supplierNo = (String) map.get("supplierNo");
        String dateFrom = (String) map.get("dateFrom");
        String dateTo = (String) map.get("dateTo");
        List<AccountingApVo> retresult = this.service.suppierViewAccount(supplierNo,dateFrom,dateTo);

        return result.success(retresult);
    }

    @ApiOperation("供应商-获得付款金额")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/getSupplierApAmount")
    public Result getSupplierApAmount(@RequestBody Map map){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String salesOrderItemNo = (String) map.get("salesOrderItemNo");
        SalesOrderItemVo salesOrderItem = salesOrderItemService.findById(salesOrderItemNo);
        String retresult = this.service.getSupplierApAmount(salesOrderItem,sysuser);

        return result.success(retresult);
    }

    @ApiOperation("批量历史结算（多个用逗号隔开）")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/batchGenerateHistoricArAp/{ids}")
    public Result batchGenerateHistoricArAp(@PathVariable String[] ids) {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        return result.success(this.service.batchGenerateHistoricArAp(Arrays.asList(ids),sysuser));
    }
    @ApiOperation("批量结算（多个用逗号隔开）")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/batchGenerateArAp/{ids}")
    public Result batchGenerateArAp(@PathVariable String[] ids) {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        return result.success(this.service.batchGenerateArAp(Arrays.asList(ids),sysuser));
    }

    @ApiOperation("结算-修复历史数据二")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/fixDataTwo")
    public Result fixDataTwo(){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String retresult = this.service.fixDataTwo(sysuser);
        return result.success(retresult);
    }
    @ApiOperation("结算-修复历史退单数据")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/fixDataThree")
    public Result fixDataThree(){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String retresult = this.service.fixDataThree(sysuser);
        return result.success(retresult);
    }
    @ApiOperation("结算-修复历史退单数据")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/fixDataFour")
    public Result fixDataFour(){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String retresult = this.service.fixDataFour(sysuser);
        return result.success(retresult);
    }
    @ApiOperation("结算-修复历史数据")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/fixData")
    public Result fixData(){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String retresult = this.service.fixData(sysuser);
        return result.success(retresult);
    }

    @ApiOperation("结算-再次批量结算失败的单据")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/regenerateArAp")
    public Result regenerateArAp(){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());

        String rt = "success";
        List<SalesOrderItemVo> notSettlements = this.salesOrderItemService.findAll(salesOrderItemSearchParam);
        for(int i = 0; i < notSettlements.size(); i++) {
            SalesOrderItemVo salesOrderItemVo = (SalesOrderItemVo) notSettlements.get(i);
            this.service.regenerateArAp(sysuser,salesOrderItemVo);
        }
        return result.success();
    }
    @ApiOperation("结算-获得全部未结算收付款金额")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/generateArAp")
    public Result generateArAp(){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        salesOrderItemSearchParam.setErrorFlag("N");
        List<SalesOrderItemVo> notSettlements = this.salesOrderItemService.findAll(salesOrderItemSearchParam);
        for(int i = 0; i < notSettlements.size(); i++) {
            SalesOrderItemVo salesOrderItemVo =(SalesOrderItemVo)notSettlements.get(i);
            this.service.generateArAp(sysuser,salesOrderItemVo);
        }
        return result.success();
    }

    @ApiOperation("登记退单")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:editPrice')")
    @PostMapping("/editPrice")
    public Result editPrice(@RequestBody AccountingApSaveParam params) {
        String ret = service.editPrice(params);
        return result.success();

    }
    @ApiOperation("结算-获得全部未结算收付款金额")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/generateMigrationArAp")
    public Result generateMigrationArAp(){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        this.service.generateMigrationArAp(sysuser);
        return result.success();
    }


    @ApiOperation("再次结算")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:confirm')")
    @PostMapping("/handleConfirmPay/{id}")
    public Result handleConfirmPay(@PathVariable String id) {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        return result.success(this.service.handleConfirmPay(id,sysuser));
    }
    @ApiOperation("再次结算")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/settleAgain/{id}")
    public Result settleAgain(@PathVariable String id) {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        return result.success(this.service.settleAgain(id,sysuser));
    }
    @ApiOperation("结算-获得所选未结算收付款金额")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/generateSelectedArAp")
    public Result generateSelectedArAp(@RequestBody Map map){
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String salesOrderItemNo = (String) map.get("salesOrderItemNo");
        SalesOrderItemVo salesOrderItem = salesOrderItemService.findById(salesOrderItemNo);
        String retresult = this.service.generateSelectedArAp(salesOrderItem,sysuser);
        return result.success(retresult);
    }
    @ApiOperation("供应商-对账减")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/handleAdjustSub")
    public Result handleAdjustSub(@RequestBody AccountingApSaveParam params){
        String mes = this.service.handleAdjustSub(params);
        return result.success(mes);
    }

    @ApiOperation("供应商-对账加")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/handleAdjustAdd")
    public Result handleAdjustAdd(@RequestBody AccountingApSaveParam params){
        String mes = this.service.handleAdjustAdd(params);
        return result.success(mes);
    }
    @ApiOperation("品牌排行列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/brandRateView/{current}/{pageSize}")
    public Result brandRateView(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.brandRateView(params, current, pageSize));
    }
    @ApiOperation("供应商排行列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/supplierRateView/{current}/{pageSize}")
    public Result supplierRateView(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.supplierRateView(params, current, pageSize));
    }

    @ApiOperation("处理退单")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/processReturn")
    public Result processReturnAll() {
        return result.success(this.service.processReturnAll());
    }

    @ApiOperation("处理退单")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/reprocessReturn")
    public Result reprocessReturn() {
        return result.success(this.service.reprocessReturn());
    }
    @ApiOperation("供应商汇总列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/skuReport/{current}/{pageSize}")
    public Result skuReport(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        IPage<AccountingApViewVo> ipages = this.service.skuReport(params, current, 1000);
        return result.success(ipages);
    }

    @ApiOperation("供应商汇总列表-分页")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/skuChartReport/{current}/{pageSize}")
    public Result skuChartReport(@RequestBody AccountingApSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
//        String xdata = "{ title:'单品日销售', xData:[";
//        String ydata = " yData:[";
//        String zdata = " zData:[";
        IPage<AccountingApViewVo> ipages = this.service.skuReport(params, current, 1000);
        List <AccountingApViewVo> accountingApViewVos =ipages.getRecords();
        Map<String, Object> rest = MapUtils.newHashMap();
        List<String> xdata = new ArrayList<String>();
        List<Double> ydata = new ArrayList<Double>();
        List<Double> zdata =new ArrayList<Double>();
        try{
            AccountingApViewVo firstaccountingApViewVo =(AccountingApViewVo)accountingApViewVos.get(0);

            xdata.add(firstaccountingApViewVo.getMonthYearDate());
            ydata.add(firstaccountingApViewVo.getSumAmtAr());
            zdata.add(firstaccountingApViewVo.getSumQty());
            String firstviewDate = firstaccountingApViewVo.getMonthYearDate();
            Date nextDate = DateUtils.parseDate(firstviewDate,"yyyy-MM-dd");
            for(int i=1; i < accountingApViewVos.size();i++){

                AccountingApViewVo accountingApViewVo =(AccountingApViewVo)accountingApViewVos.get(i);
                nextDate = DateUtils.getDateAfter(nextDate,1);
                String shouldBeDate =DateUtils.formatDate(nextDate);
                String viewDate = accountingApViewVo.getMonthYearDate();
                Date accountingApViewDate = DateUtils.parseDate(viewDate);
                if(!shouldBeDate.equals(viewDate)){
                    double days = DateUtils.getDistanceOfTwoDate(nextDate,accountingApViewDate);
                    int intdays= Double.valueOf(days).intValue();
                    for(int j=0;j<intdays;j++){
                        //   AccountingApViewVo salesisZeroAccountingApViewVo = new AccountingApViewVo();
                        String adddate = DateUtils.formatDate(nextDate);
                        //    salesisZeroAccountingApViewVo.setMonthYearDate(adddate);
                        //    salesisZeroAccountingApViewVo.setSumAmtAr(0.00);
                        //    salesisZeroAccountingApViewVo.setSumQty(0.00);
                        //    accountingApViewVos.add(i,salesisZeroAccountingApViewVo);
                        nextDate = DateUtils.getDateAfter(nextDate,1);

                        xdata.add(adddate);
                        ydata.add(0.00);
                        zdata.add(0.00);
                    }
                    xdata.add(accountingApViewVo.getMonthYearDate());
                    ydata.add(accountingApViewVo.getSumAmtAr());
                    zdata.add(accountingApViewVo.getSumQty());
                }else{
                    xdata.add(accountingApViewVo.getMonthYearDate());
                    ydata.add(accountingApViewVo.getSumAmtAr());
                    zdata.add(accountingApViewVo.getSumQty());
                }
            }
        }catch(Exception e){
            e.printStackTrace();

        }
        rest.put("title", "单品日销售");
        rest.put("xData", xdata);
        rest.put("yData", ydata);
        rest.put("zData", zdata);


//        for(int i=0; i < accountingApViewVos.size();i++){
//            AccountingApViewVo accountingApViewVo =(AccountingApViewVo)accountingApViewVos.get(i);
//            if(i==accountingApViewVos.size()-1){
//                xdata = xdata.concat("'").concat(accountingApViewVo.getMonthYearDate()).concat("'],");
//                ydata = ydata.concat(String.valueOf(accountingApViewVo.getSumAmtAr())).concat("],");
//                zdata = zdata.concat(String.valueOf(accountingApViewVo.getSumQty())).concat("]");
//            }else{
//                xdata = xdata.concat("'").concat(accountingApViewVo.getMonthYearDate()).concat("',");
//                ydata = ydata.concat(String.valueOf(accountingApViewVo.getSumAmtAr())).concat(",");
//                zdata = zdata.concat(String.valueOf(accountingApViewVo.getSumQty())).concat(",");
//            }
//        }
//        String rest = xdata.concat(ydata).concat(zdata).concat("}");


        //     List<String> xdata = accountingApViewVos.stream().map(AccountingApViewVo::getMonthYearDate).collect(Collectors.toList());
        //     List<Double> ydata = accountingApViewVos.stream().map(AccountingApViewVo::getSumAmtAr).collect(Collectors.toList());
        //     List<Double> zdata = accountingApViewVos.stream().map(AccountingApViewVo::getSumQty).collect(Collectors.toList());
        return result.success(rest);
    }

    @ApiOperation("处理退单")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/batchProcessReturn/{ids}")
    public Result processReturn(@PathVariable String[] ids) {
        return result.success(this.service.processReturn(Arrays.asList(ids)));
    }
    @ApiOperation("销售金额汇总-当天查询")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/countTotalTodayPurchase")
    public Result countTotalTodayPurchase() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccountingApSearchParam accountingApSearchParam = new AccountingApSearchParam();
        Date today = new Date();

        Date yesterday = DateUtils.getDateBefore(today,1);
        String datestr = DateUtils.formatDate(yesterday);
        accountingApSearchParam.setJobDate(datestr);
        return result.success(this.service.countTotalTodayPurchase(accountingApSearchParam));
    }
    @ApiOperation("销售金额汇总-当天查询")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/countTodayTotalSale")
    public Result countTodayTotalSale() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccountingApSearchParam accountingApSearchParam = new AccountingApSearchParam();
        Date today = new Date();
        String datestr = DateUtils.formatDate(DateUtils.getDateBefore(today, 1));
        accountingApSearchParam.setJobDate(datestr);
        return result.success(this.service.countTodayTotalSale(accountingApSearchParam));
    }
    @ApiOperation("导出")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/exportData")
    public Result exportData(@RequestBody AccountingApSearchParam params) {
        return result.success(this.service.exportData(params));
    }

    @ApiOperation("导出报表")
    @PreAuthorize("hasAnyAuthority('accounting:accountingAp:search')")
    @PostMapping("/exportreportData")
    public Result exportreportData(@RequestBody AccountingApSearchParam params) {
        return result.success(this.service.exportreportData(params));
    }

    @ApiOperation("导入")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:insert')")
    @PostMapping("/importOrderData")
    public Result importData(String customerNo, MultipartFile file) {
        List<SalesOrderItemVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        CustomerVo customerVo = iCustomerService.findById(customerNo);

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(SalesOrderItemVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            //return "没有读取到数据";
            log.error("没有读取到数据!");
        }
        SalesOrderItemVo firstdata = (SalesOrderItemVo)dataList.get(0);
        String custOrderNo ="";
        SalesOrder newSalesOrder = null;
        int itemNo = 0;
        int line = 0;
        List<String> custOrderNos = new ArrayList<String>();
        for (SalesOrderItemVo data : dataList) {
            successNum++;
            line++;
            // if(!data.getCustSalesOrderNo().equals(custOrderNo)){
            custOrderNo = data.getCustSalesOrderNo();
            if (!custOrderNos.contains(custOrderNo)) {
                newSalesOrder=   this.service.importData(customerNo, data,custOrderNo,user,itemNo,line, customerVo,newSalesOrder);
                custOrderNo = data.getCustSalesOrderNo();
                custOrderNos.add(custOrderNo);
            }else{
                newSalesOrder=this.service.importData(customerNo, data,"No",user,itemNo,line,customerVo,newSalesOrder);
            }
            itemNo = itemNo++;
        }

        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");


        return result.success(successMsg.toString());
    }
}
